package com.xiu.travel.annotation;


import com.xiu.travel.util.IPUtils;
import com.xiu.travel.util.api.CommonResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.AnnotatedElementUtils;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

import java.io.Serial;
import java.lang.annotation.Annotation;

/**
 * @author qianl
 */
@Slf4j
@ControllerAdvice
public class ResponseRHandler implements ResponseBodyAdvice<Object> {

    @Serial
    final Class<? extends Annotation> ANNOTATION_TYPE = ResponseR.class;


    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
       return AnnotatedElementUtils.hasAnnotation(returnType.getContainingClass(),ANNOTATION_TYPE)||
               returnType.hasMethodAnnotation(ANNOTATION_TYPE);
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        System.out.println(IPUtils.getIpAddr());
        return body instanceof CommonResult ? body : CommonResult.success(body);
    }
}
